<template>
  <div class="register-container">
    <div class="auth-decor" aria-hidden="true">
      <span class="blob b1"></span>
      <span class="blob b2"></span>
      <span class="blob b3"></span>
      <span class="grid"></span>
    </div>
    <div class="register-box">
      <div class="register-header">
        <h2>用户注册</h2>
        <p>创建您的账户，开始使用我们的服务</p>
      </div>

      <el-tabs v-model="registerType" class="register-tabs">
        <!-- 普通注册 -->
        <el-tab-pane label="账号注册" name="normal">
          <el-form
            ref="registerFormRef"
            :model="registerForm"
            :rules="registerRules"
            class="register-form"
            label-position="top"
          >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名（4-20个字符）"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码（6-20个字符）"
            size="large"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            size="large"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="昵称（可选）" prop="nickname">
          <el-input
            v-model="registerForm.nickname"
            placeholder="请输入昵称"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><Avatar /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="邮箱（可选）" prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱地址"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="手机号（可选）" prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><Phone /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="captchaCode">
          <div style="display: flex; gap: 10px;">
            <el-input
              v-model="registerForm.captchaCode"
              placeholder="请输入验证码"
              size="large"
              clearable
              maxlength="4"
              style="flex: 1;"
            >
              <template #prefix>
                <el-icon><Key /></el-icon>
              </template>
            </el-input>
            <div 
              class="captcha-image"
              @click="refreshCaptcha"
              :title="'点击刷新验证码'"
            >
              <img v-if="captchaImage" :src="captchaImage" alt="验证码" />
              <el-icon v-else class="refresh-icon"><RefreshRight /></el-icon>
            </div>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="register-btn"
            :loading="loading"
            @click="handleRegister"
          >
            {{ loading ? '注册中...' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>

    <!-- 邮箱注册 -->
    <el-tab-pane label="邮箱注册" name="email">
      <el-form
        ref="emailRegisterFormRef"
        :model="emailRegisterForm"
        :rules="emailRegisterRules"
        class="register-form"
        label-position="top"
      >
        <el-form-item label="邮箱" prop="email">
          <el-input
            v-model="emailRegisterForm.email"
            placeholder="请输入邮箱地址"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <el-input
            v-model="emailRegisterForm.code"
            placeholder="请输入验证码"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><Key /></el-icon>
            </template>
            <template #append>
              <el-button
                :disabled="countdown > 0"
                @click="handleSendCode"
              >
                {{ countdown > 0 ? `${countdown}秒后重试` : '发送验证码' }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="emailRegisterForm.password"
            type="password"
            placeholder="请输入密码（6-20个字符）"
            size="large"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="emailRegisterForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            size="large"
            show-password
            clearable
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="昵称（可选）" prop="nickname">
          <el-input
            v-model="emailRegisterForm.nickname"
            placeholder="请输入昵称"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><Avatar /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="large"
            class="register-btn"
            :loading="loading"
            @click="handleEmailRegister"
          >
            {{ loading ? '注册中...' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-tab-pane>
  </el-tabs>

  <div class="register-footer">
    <span>已有账号？</span>
    <router-link to="/login" class="login-link">立即登录</router-link>
  </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '@/stores/user'
import { User, Lock, Avatar, Message, Phone, Key, RefreshRight } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { sendEmailCode, registerByEmail, getCaptcha } from '@/api/auth'

const userStore = useUserStore()
const registerFormRef = ref(null)
const emailRegisterFormRef = ref(null)
const loading = ref(false)
const registerType = ref('normal')
const countdown = ref(0)
let timer = null

// 验证码相关
const captchaKey = ref('')
const captchaImage = ref('')

// 普通注册表单数据
const registerForm = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  nickname: '',
  email: '',
  phone: '',
  captchaCode: ''
})

// 邮箱注册表单数据
const emailRegisterForm = reactive({
  email: '',
  code: '',
  password: '',
  confirmPassword: '',
  nickname: ''
})

// 自定义验证规则
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (registerForm.confirmPassword !== '') {
      registerFormRef.value.validateField('confirmPassword')
    }
    callback()
  }
}

const validateConfirmPass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const validateEmailConfirmPass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== emailRegisterForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度在4-20个字符之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPass, trigger: 'blur' }
  ],
  nickname: [
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/, message: '邮箱格式不正确', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  captchaCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 4, message: '验证码为4位', trigger: 'blur' }
  ]
}

const emailRegisterRules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { len: 6, message: '验证码为6位数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateEmailConfirmPass, trigger: 'blur' }
  ],
  nickname: [
    { max: 50, message: '昵称长度不能超过50个字符', trigger: 'blur' }
  ]
}

// 获取验证码
const loadCaptcha = async () => {
  try {
    const res = await getCaptcha()
    if (res.code === 200) {
      captchaKey.value = res.data.key
      captchaImage.value = res.data.image
    }
  } catch (error) {
    console.error('获取验证码失败:', error)
  }
}

// 刷新验证码
const refreshCaptcha = () => {
  loadCaptcha()
  registerForm.captchaCode = ''
}

// 普通注册处理
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await userStore.userRegister({
          ...registerForm,
          captchaKey: captchaKey.value
        })
      } catch (error) {
        console.error('注册失败:', error)
        // 注册失败后刷新验证码
        refreshCaptcha()
      } finally {
        loading.value = false
      }
    } else {
      ElMessage.warning('请填写完整的注册信息')
    }
  })
}

// 组件挂载时加载验证码
onMounted(() => {
  loadCaptcha()
})

// 发送验证码
const handleSendCode = async () => {
  if (!emailRegisterForm.email) {
    ElMessage.warning('请先输入邮箱')
    return
  }
  
  // 验证邮箱格式
  const emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
  if (!emailReg.test(emailRegisterForm.email)) {
    ElMessage.warning('邮箱格式不正确')
    return
  }
  
  try {
    // 发送验证码，类型为register
    await sendEmailCode(emailRegisterForm.email, 'register')
    ElMessage.success('验证码已发送，请查收邮件')
    
    // 开始倒计时
    countdown.value = 60
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '发送验证码失败')
  }
}

// 邮箱注册处理
const handleEmailRegister = async () => {
  if (!emailRegisterFormRef.value) return
  
  await emailRegisterFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const res = await registerByEmail({
          email: emailRegisterForm.email,
          code: emailRegisterForm.code,
          password: emailRegisterForm.password,
          nickname: emailRegisterForm.nickname
        })
        
        console.log('注册响应:', res)
        console.log('注册数据:', res.data)
        
        // 检查返回数据
        if (!res.data) {
          console.error('返回数据为空')
          ElMessage.error('注册失败：返回数据为空')
          return
        }
        
        // 保存登录信息到 store 和 localStorage
        userStore.token = res.data.accessToken
        userStore.refreshToken = res.data.refreshToken
        userStore.userInfo = res.data.userInfo
        
        localStorage.setItem('token', res.data.accessToken)
        localStorage.setItem('refreshToken', res.data.refreshToken)
        localStorage.setItem('userInfo', JSON.stringify(res.data.userInfo))
        
        // 获取用户完整信息（角色、权限、菜单）
        await userStore.fetchUserFullInfo(res.data.userInfo.id)
        
        ElMessage.success('注册成功，正在跳转...')
        // 跳转到首页
        setTimeout(() => {
          window.location.href = '/home'
        }, 500)
      } catch (error) {
        console.error('注册错误:', error)
        console.error('错误详情:', error.response)
        ElMessage.error(error.response?.data?.message || error.message || '注册失败')
      } finally {
        loading.value = false
      }
    } else {
      ElMessage.warning('请填写完整的注册信息')
    }
  })
}
</script>

<style scoped>
.register-container {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 20px 0;
  background: #0a0a0a;
  overflow: hidden;
}

.register-box {
  position: relative;
  z-index: 10;
  width: 480px;
  padding: 48px 40px;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
}

.register-tabs {
  margin-bottom: 10px;
}

.register-tabs :deep(.el-tabs__nav-wrap::after) {
  display: none;
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.register-header h2 {
  font-size: 26px;
  font-weight: 600;
  color: #0a0a0a;
  margin-bottom: 8px;
  letter-spacing: -0.02em;
}

.register-header p {
  font-size: 14px;
  color: #737373;
  font-weight: 400;
}

.register-form {
  margin-top: 20px;
}

.register-btn {
  width: 100%;
  font-size: 16px;
  height: 44px;
}

.register-footer {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #666;
}

.login-link {
  color: var(--el-color-primary);
  text-decoration: none;
  margin-left: 5px;
  font-weight: 500;
}

.login-link:hover {
  color: var(--el-color-primary-dark-2);
  text-decoration: underline;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

.captcha-image {
  width: 120px;
  height: 40px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  transition: all 0.3s;
}

.captcha-image:hover {
  border-color: var(--el-color-primary);
}

.captcha-image img {
  width: 100%;
  height: 100%;
  display: block;
}

.refresh-icon {
  font-size: 24px;
  color: #909399;
}

/* Cursor-style center glow effect */
.auth-decor {
  position: absolute;
  inset: 0;
  overflow: hidden;
  pointer-events: none;
}

.auth-decor .blob {
  position: absolute;
  border-radius: 50%;
  filter: blur(80px);
  opacity: 0.6;
  animation: pulse 8s ease-in-out infinite;
}

.auth-decor .b1 {
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 600px;
  height: 600px;
  background: radial-gradient(circle, rgba(59, 130, 246, 0.35), transparent 70%);
}

.auth-decor .b2 {
  top: 30%;
  left: 20%;
  width: 400px;
  height: 400px;
  background: radial-gradient(circle, rgba(14, 165, 233, 0.25), transparent 70%);
  animation-delay: -2s;
}

.auth-decor .b3 {
  bottom: 20%;
  right: 15%;
  width: 450px;
  height: 450px;
  background: radial-gradient(circle, rgba(6, 182, 212, 0.3), transparent 70%);
  animation-delay: -4s;
}

@keyframes pulse {
  0%, 100% {
    opacity: 0.6;
    transform: translate(-50%, -50%) scale(1);
  }
  50% {
    opacity: 0.8;
    transform: translate(-50%, -50%) scale(1.05);
  }
}

.auth-decor .grid {
  display: none;
}

/* Dark theme adaptation */
.dark .register-container {
  background: #0a0a0a;
}

.dark .register-box {
  background: rgba(20, 20, 20, 0.95);
  border: 1px solid rgba(255, 255, 255, 0.08);
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
}

.dark .register-header h2 {
  color: #fafafa;
}

.dark .register-header p {
  color: #a3a3a3;
}
</style>